package com.yingpai.fitness.dvp_2_0.main.activity.mine.integral;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.donkingliang.labels.LabelsView;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.GsonUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;
import com.yingpai.fitness.dvp_2_0.main.activity.shop.PhotoActivity;
import com.yingpai.fitness.dvp_2_0.main.bean.ShopServiceCom;
import com.yingpai.fitness.dvp_2_0.main.bean.integral.IntegralMallDetail;
import com.yingpai.fitness.dvp_2_0.main.util.DialogUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.CornersTransform;
import com.yingpai.fitness.dvp_2_0.main.widget.GlideImageLoader;
import com.yingpai.fitness.dvp_2_0.main.widget.MyBanner;
import com.yingpai.fitness.entity.ShopDetailMcipBean;
import com.yingpai.fitness.entity.ShopDetailMcipChildBean;
import com.yingpai.fitness.entity.shop.detail.PhotoEventMessage;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import com.zzhoujay.richtext.RichText;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 积分商品详情
 * Created by ASUS on 2018/12/19.
 */

public class IntegralMallShopDetailActivity extends CommonActivity {
    @BindView(R.id.right_tv)
    TextView rightTv;
    @BindView(R.id.commDetailVp)
    MyBanner commDetailVp;
    @BindView(R.id.title_tv)
    TextView title_tv;
    @BindView(R.id.integral)
    TextView integral;
    //    @BindView(R.id.textview1)
//    TextView textview1;
//    @BindView(R.id.linearLayout1)
//    LinearLayout linearLayout1;
    @BindView(R.id.textview2)
    TextView textview2;
    @BindView(R.id.discountVip)
    TextView discountVip;
    @BindView(R.id.linearLayout2)
    LinearLayout linearLayout2;
    @BindView(R.id.shopInfomationWb)
    TextView shopInfomationWb;
    @BindView(R.id.scrollview)
    NestedScrollView scrollview;

    @BindView(R.id.servicepromise)
    RelativeLayout mlayout_servicepromise;
    @BindView(R.id.id_flowlayout)
    TagFlowLayout mTagFlowLayout;
    private TokenBean tokenBean;
    private Dialog dialog;
    private String id;
    private IntegralMallDetail mIntegralMallDetail;
    private XListView mciplistview;
    private QuickAdapter<IntegralMallDetail.DataBean.PropertySetBean> mcipadapter;
    private LayoutInflater mInflater;
    private StringBuilder sb = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.activity_integral_mall_shop_detail);
    }

    @Override
    protected void initView() {
        setTitle("商品详情");
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            id = bundle.getString("id");
        }
//        Drawable drawableLeft = getResources().getDrawable(
//                R.mipmap.share);
//        rightTv.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,
//                null, null, null);

        final int startColor = ContextCompat.getColor(this, R.color.normal_status);
        final int endColor = ContextCompat.getColor(this, R.color.colorNavigation);

        scrollview.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int headHeight = commDetailVp.getHeight();
                int scrollDistance = Math.min(scrollY, headHeight);
                float fraction = (float) scrollDistance / (float) headHeight;

//                setToolbarStatusBarAlpha(evaluate(fraction, startColor, endColor),titleBar);
                setNavigationViewColor(evaluate(fraction, startColor, endColor));
            }
        });

        mInflater = LayoutInflater.from(this);
    }

    @Override
    protected void initData() {
        requestData();
    }

    private void requestData() {
        showDialog(this,null);
        HashMap<String,Object> params = new HashMap();
        params.put("id", id);
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.INTEGRAL_MALL_DETAIL,
                params, Url.INTEGRAL_MALL_DETAIL, new Callback<IntegralMallDetail>() {
            @Override
            public void onSuccess(IntegralMallDetail integralMallDetail) {
                if (integralMallDetail.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                    mIntegralMallDetail = integralMallDetail;

                    integralMallDetail.getData().setMicpBeanList(GsonUtil.jsonToList(integralMallDetail.getData().getMcipList(), ShopDetailMcipBean.class));

                    for (int i = 0; i < integralMallDetail.getData().getMicpBeanList().size(); i++) {
                        List<ShopDetailMcipChildBean> list = GsonUtil.jsonToList(integralMallDetail.getData().getMicpBeanList().get(i).getPropertyValue(), ShopDetailMcipChildBean.class);
                        Comparator comparator = Collections.reverseOrder();
                        Collections.sort(list, comparator);
                        integralMallDetail.getData().getMicpBeanList().get(i).setProperty(list);
                    }

                    Comparator comparator = Collections.reverseOrder();
                    Collections.sort(integralMallDetail.getData().getPropertySet(), comparator);

                    for (int j = 0; j < integralMallDetail.getData().getPropertySet().size(); j++) {
                        List<String> list = new ArrayList<>();
                        for (int i = 0; i < integralMallDetail.getData().getMicpBeanList().size(); i++) {
                            if (!list.contains(integralMallDetail.getData().getMicpBeanList().get(i).getProperty().get(j).getPropertyValue())) {
                                list.add(integralMallDetail.getData().getMicpBeanList().get(i).getProperty().get(j).getPropertyValue());
                            }
                        }
                        integralMallDetail.getData().getPropertySet().get(j).setList(list);
                    }

                    commDetailVp.setOnBannerListener(new OnBannerListener() {
                        @Override
                        public void OnBannerClick(int position) {
                            EventBus.getDefault().postSticky(new PhotoEventMessage(position, Arrays.asList(mIntegralMallDetail.getData().getMerchandise().getPhotoUrls().split(","))));
                            startActivity(PhotoActivity.class);
                        }
                    });

                    commDetailVp.setImages(Arrays.asList(mIntegralMallDetail.getData().getMerchandise().getPhotoUrls().split(",")))
                            .setBannerStyle(BannerConfig.NUM_INDICATOR)
                            .setIndicatorGravity(BannerConfig.CENTER)
                            .setImageLoader(new GlideImageLoader())
                            .start();

                    title_tv.setText(mIntegralMallDetail.getData().getMerchandise().getMerchandiseName());
                    integral.setText(mIntegralMallDetail.getData().getMerchandise().getExchangePoint()+"");

                    RichText.fromHtml(mIntegralMallDetail.getData().getMerchandiseDetail().getDetailInfo()).into(shopInfomationWb);

                    if(!TextUtils.isEmpty(mIntegralMallDetail.getData().getDiscountDesp())){
//                        String disCount = "开通会员立享"+mIntegralMallDetail.getData().getDiscount()+"折";
//
//                        SpannableStringBuilder builder = new SpannableStringBuilder(disCount);
//                        ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.parseColor("#FFFF5656"));
//                        builder.setSpan(redSpan,6,6+mIntegralMallDetail.getData().getDiscount().length(),
//                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        discountVip.setText(mIntegralMallDetail.getData().getDiscountDesp());
                    }else{
                        discountVip.setVisibility(View.GONE);
                    }


                    if(null != mIntegralMallDetail.getData().getServiceCommitment()){
                        if(mIntegralMallDetail.getData().getServiceCommitment().size() > 0){
                            mTagFlowLayout.setAdapter(new TagAdapter<IntegralMallDetail.DataBean.ServiceCommitmentBean>
                                    (mIntegralMallDetail.getData().getServiceCommitment())
                            {
                                @Override
                                public View getView(FlowLayout parent, int position,
                                                    IntegralMallDetail.DataBean.ServiceCommitmentBean bean)
                                {
                                    TextView tv = (TextView) mInflater.inflate(R.layout.flow_tv_layout, mTagFlowLayout, false);
                                    tv.setText(bean.getTitle());
                                    return tv;
                                }
                            });
                            mTagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
                            {
                                @Override
                                public boolean onTagClick(View view, int position, FlowLayout parent)
                                {
                                    ejectFrame();
                                    return true;
                                }
                            });
                            for (int i = 0; i < mIntegralMallDetail.getData().getServiceCommitment().size(); i++) {
                                sb.append(mIntegralMallDetail.getData().getServiceCommitment().get(i).getId()).append(",");
                            }
                            sb.substring(0,sb.toString().length()-1);
                        }else{
                            mlayout_servicepromise.setVisibility(View.GONE);
                        }
                    }else{
                        mlayout_servicepromise.setVisibility(View.GONE);
                    }
                } else {
                    showToast(integralMallDetail.getMessage() + "");
                }

                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }



    @Override
    @OnClick({R.id.right_tv, R.id.select_spec, R.id.bottom_tv,R.id.servicepromise})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.right_tv:
                break;
            case R.id.select_spec:
                buyDialog();
                break;
            case R.id.bottom_tv:
                buyDialog();
                break;
            case R.id.servicepromise:
                ejectFrame();
                break;
        }
    }

    private void buyDialog() {
        View bottom_buy = View.inflate(this, R.layout.bottom_integral_mall_buy, null);
        dialog = new Dialog(this, R.style.ShopDialogStyle);
        dialog.setContentView(bottom_buy);

        bottom_buy.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        RelativeLayout buySubtractIv = (RelativeLayout) bottom_buy.findViewById(R.id.buySubtractIv);
        RelativeLayout buyAddIv = (RelativeLayout) bottom_buy.findViewById(R.id.buyAddIv);
        final TextView buyNumEt = (TextView) bottom_buy.findViewById(R.id.buyNumEt);
        buySubtractIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.parseInt(buyNumEt.getText().toString()) - 1 >= 1) {
                    buyNumEt.setText(Integer.parseInt(buyNumEt.getText().toString()) - 1 + "");
                }
            }
        });
        buyAddIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buyNumEt.setText(Integer.parseInt(buyNumEt.getText().toString()) + 1 + "");
            }
        });
        ImageView photo = bottom_buy.findViewById(R.id.photo);
        Glide.with(this)
                .load(mIntegralMallDetail.getData().getMerchandise().getPhotoUrls().split(",")[0])
                .transform(new CornersTransform(this, 20))
                .error(R.mipmap.default_small_bg)
                .into(photo);
        TextView member_price = bottom_buy.findViewById(R.id.member_price);
        member_price.setText(mIntegralMallDetail.getData().getMerchandise().getExchangePoint()+"");

        mciplistview = bottom_buy.findViewById(R.id.mciplistview);

        mcipadapter = new QuickAdapter<IntegralMallDetail.DataBean.PropertySetBean>(this, R.layout.item_shop_mciplist_parent) {
            @Override
            protected void convert(BaseAdapterHelper helper, final IntegralMallDetail.DataBean.PropertySetBean item) {
                helper.setText(R.id.title, item.getPropertyName() + ":");

                LabelsView labels = helper.getView(R.id.labels);

                labels.setOnLabelSelectChangeListener(new LabelsView.OnLabelSelectChangeListener() {
                    @Override
                    public void onLabelSelectChange(TextView textView, Object o, boolean b, int i) {
                        item.setIsAbandoned(b);
                        item.setPropertyValue(o + "");
                    }
                });

                labels.setLabels(item.getList());
            }
        };

        mciplistview.setAdapter(mcipadapter);
        mciplistview.setFocusable(false);

        mcipadapter.clear();
        mcipadapter.addAll(mIntegralMallDetail.getData().getPropertySet());
        mcipadapter.notifyDataSetChanged();


        bottom_buy.findViewById(R.id.bottom_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < mcipadapter.getCount(); i++) {
                    if (!mcipadapter.getItem(i).isIsAbandoned()) {
                        showToast("请选择商品规格");
                        return;
                    }
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("propertyId", mcipadapter.getItem(i).getId());
                        jsonObject.put("propertyValue", mcipadapter.getItem(i).getPropertyValue());
                        jsonArray.put(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                Logger.e(mIntegralMallDetail.getData().getId());
                Bundle bundle = new Bundle();
                bundle.putString("merchandiseId", mIntegralMallDetail.getData().getId());
                bundle.putString("merchandiseJson", jsonArray.toString());
                bundle.putInt("purchaseAmount", Integer.parseInt(buyNumEt.getText().toString()));
                startActivity(IntegralMallSureOrderActivity.class, bundle);
                finishActivity();
                dialog.dismiss();
            }
        });

        Window dialogWindow = dialog.getWindow();
        WindowManager m = dialogWindow.getWindowManager();
        Display d = m.getDefaultDisplay();
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.x = 0;
        lp.y = 0;
        lp.height = (int) d.getHeight() / 3 * 2;
        lp.width = d.getWidth();
        // 设置显示位置
        dialog.onWindowAttributesChanged(lp);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);

        dialog.show();
    }


    /**
     * 弹出框
     */
    private QuickAdapter<ShopServiceCom.DataBean> adapter;
    private void ejectFrame() {
        showDialog(this,"");
        HashMap<String,Object> httpParams = new HashMap<>();
        httpParams.put("ids",sb.toString());
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.OBTAINSERVICECOM,
                httpParams, Url.OBTAINSERVICECOM, new Callback<ShopServiceCom>() {

                    @Override
                    public void onSuccess(ShopServiceCom shopDetailBean) {
                        dismissDialog();
                        if(shopDetailBean.getCode().equals("0")){
                            DialogUtil.getInstance().showBottomDialog(context, R.layout.dialog_service_com);
                            LinearLayout zoneLayout = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;
                            ListView listView = zoneLayout.findViewById(R.id.service_lv);
                            adapter = new QuickAdapter<ShopServiceCom.DataBean>(context,R.layout.item_service) {
                                @Override
                                protected void convert(BaseAdapterHelper helper, ShopServiceCom.DataBean item) {
                                    helper.setText(R.id.service_title,item.getTitle());
                                    helper.setText(R.id.service_content,item.getDescribe());
                                }
                            };
                            listView.setAdapter(adapter);
                            adapter.clear();
                            adapter.addAll(shopDetailBean.getData());
                            zoneLayout.findViewById(R.id.ikown).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DialogUtil.getInstance().dialog_bottom.dismiss();
                                }
                            });
                        }else{
                            showToast(shopDetailBean.getMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
    }
}
